// src/utils/locationDelta.ts
import Taro from '@tarojs/taro';
import store from '@/src/store';
import { updateInfoFun } from '@/src/common/method/userInfoFun';
import { getConversionFun } from '../common/method/commonFun';
import { userInfoFun } from '../common/method/loginFun';

const SCOPE = 'scope.userLocation' as const;
const KEY_LAST_AUTH = 'LOC_LAST_AUTH_BOOL'; // '1' | '0'
const KEY_LAST_SENT_PROV = 'LOC_LAST_SENT_PROV'; // string

/** 读取/写入快照 */
const readLastAuth = (): boolean | null => {
  const raw = Taro.getStorageSync(KEY_LAST_AUTH);
  if (raw === '1') return true;
  if (raw === '0') return false;
  return null;
};
const writeLastAuth = (v: boolean) =>
  Taro.setStorageSync(KEY_LAST_AUTH, v ? '1' : '0');
const readLastSentProv = (): string =>
  Taro.getStorageSync(KEY_LAST_SENT_PROV) || '';
const writeLastSentProv = (name: string) =>
  Taro.setStorageSync(KEY_LAST_SENT_PROV, name || '');

/** 清空位置信息 */
const clearLocationInStore = () => {
  store.commonStore.setCity('');
  store.commonStore.setCityCode('');
  store.commonStore.setProvinceCode('');
  store.commonStore.setProvince('');
};

/**
 * 在切到前台时调用：
 * - 若未授权：如之前是已授权 → 清空；无论如何都不请求定位
 * - 若已授权：请求定位 + 逆地理；若省份变化 或 本会话尚未上报 → 更新后台（仅一次）
 */
export async function onAppShowCheckLocation(): Promise<void> {
  // 1) 当前真实权限
  let authed = false;
  try {
    const setting = await Taro.getSetting();
    authed = !!setting.authSetting?.[SCOPE];
  } catch {
    // 拿不到设置就啥也不做，避免误清空
    return;
  }

  const prevAuth = readLastAuth();
  writeLastAuth(authed);

  if (!authed) {
    // 权限关闭：仅当之前是已授权或当前 store 有值时清空
    if (prevAuth === true || store.commonStore.province) {
      clearLocationInStore();
    }
    return;
  }

  // 2) 已授权：拉一次定位 + 逆地理
  try {
    const loc = await Taro.getLocation({
      type: 'gcj02',
    });
    const location = `${loc.latitude},${loc.longitude}`;
    const res: any = await getConversionFun(location);

    const cityName = res?.city?.areaName || '';
    const cityCode = res?.city?.areaCode || '';
    const provName = res?.province?.areaName || '';
    const provCode = res?.province?.areaCode || '';

    // 写入 store
    store.commonStore.setCity(cityName);
    store.commonStore.setCityCode(cityCode);
    store.commonStore.setProvinceCode(provCode);
    store.commonStore.setProvince(provName);

    // 3) 仅在「位置变化」或「本会话尚未上报」时，更新后台一次
    await maybeUpdateBackendOncePerSession(provName);
  } catch {
    // 拿不到定位或逆地理失败：不改动已有 store（避免闪烁）
    // 也不调用后台
  }
}

/**
 * 只在本会话未上报过 或 省份发生变化时，上报一次后台；
 * 上报成功后：
 *  - 存储 lastSentProv = 当前省份
 *  - store.commonStore.setNeedUpdateInfo(false)
 */
async function maybeUpdateBackendOncePerSession(
  currentProv: string
): Promise<void> {
  // 无有效省份，不上报
  if (!currentProv) return;

  const need = store.commonStore.needUpdateInfo !== false; // 默认 true
  const lastSent = readLastSentProv();
  const changed = currentProv !== lastSent;

  if (!need && !changed) return;

  const res: any = await userInfoFun({
    access_token: store.commonStore.accessToken,
  });
  try {
    await updateInfoFun({
      ucUserId: res.userId,
      ucLoginPhone: res.mobile,
      ucNickname: Taro.getStorageSync(`nickname-${res.userId}`),
      ucAvatarUrl: res.avatarUrl,
      address: currentProv, // 你要的省份
    });
    // 成功：标记为已上报 & 记录最新省份
    store.commonStore.setNeedUpdateInfo(false);
    writeLastSentProv(currentProv);
  } catch {
    // 失败：不改变 needUpdateInfo，下次切前台继续尝试
  }
}

/** 进入后台时记一份权限快照（可选） */
export async function onAppHideSnapshotAuth(): Promise<void> {
  try {
    const s = await Taro.getSetting();
    writeLastAuth(!!s.authSetting?.[SCOPE]);
  } catch {}
}

/** App 启动时：初始化「需要上报」标记为 true（退出重进后需要再次更新） */
export function markNeedUpdateOnLaunch() {
  store.commonStore.setNeedUpdateInfo(true);
}
